package com.ecreditpal.audio.platform;

import com.ecreditpal.audio.AsrRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lifeng
 * @version 1.0 on 2018/7/8.
 */
@Component
public class PlatformBalancer {

    @Autowired
    private PlatformConfig platformConfig;

    private List<AsrRunner> runners = new ArrayList<>();

    private final AtomicInteger nextIndex = new AtomicInteger();




    @PostConstruct
    public void init() throws IllegalAccessException, InstantiationException {
        for (String s : platformConfig.getConfig().keySet()) {
            Config config = platformConfig.getConfig().get(s);
            AsrRunner runner = (AsrRunner) Config.PLATFORMS.get(s).newInstance();
            runner.init(config);
            runners.add(runner);
        }

    }


    /**
     * 轮询的方式获得一个runner
     * @return
     */
    public AsrRunner chooseRunner() {
        int index = incrementAndGetModulo(runners.size());
        return runners.get(index);
    }

    public AsrRunner getLongRunner() {
        return runners.get(0);
    }


    /**
     * 取模轮询
     * @param modulo
     * @return
     */
    private int incrementAndGetModulo(int modulo) {
        for (;;) {
            int current = nextIndex.get();
            int next = (current + 1) % modulo;
            if (nextIndex.compareAndSet(current, next) && current < modulo)
                return current;
        }
    }


}
